# -*- coding: ISO-8859-1 -*-
"""\
Converter base

Defines generic tools for converting data to the BibTeX format.

The philosophy of BibConverter is to split the the conversion process into
two parts. 
1. The input data is analyzed and the relevant data is put into a dictionary.
2. The dictionary from step one is used to create a BibTeX record.

"""

# Copyright (c) 2007 Kjell Magne Fauske
# See LICENSE for details.


import bibtexbib
import biblibutils
from sets import Set

class ToBibTeXConverter:
    """A ceneric class for converting bibliographic data to the BibTeX format"
    
    Tries to solve the conversion problem without using an endless list of
    IFs and ELSEs. The input data to the converter is a dictionary of key and
    value pairs. 
    """
    def __init__(self, inputdata, entry_info, options = {}):
        """Initialize class
        
        Input:
            inputdata - A dictionary where key is field names and value
                is data.
            entry_info - 
            options -
        
        """
        self.bibtexentry = bibtexbib.BibTeXEntry()
        self.entry = inputdata
        self.unused_fields = Set(self.entry.keys())
        self.entry_info = entry_info
        self.options = options
        self.formatter = bibtexbib.BibTeXFormatter(self.bibtexentry, 
                                                   self.options)
    def getField(self, key, default=None):
        val = self.entry.get(key, None)
        if val:
            self.unused_fields -= Set([key])
            return val
        return default
        
    def defaultHandler(self, fieldname):
        pass
        
    def unusedHandler(self):
        pass
        
    def convert(self):
        # process required and optional fields
        if self.entry_info == None:
            self.bibtexentry = None
            return
        for field in self.entry_info["required"]+self.entry_info['optional']:
            handler_name = field+'Handler'
            handler = getattr(self, handler_name, None)
            if handler: 
                handler()
            else:
                self.defaultHandler(field)
        #
        # output unused fields
        self.unusedHandler()
        self.formatter.format()

